import router from "./router"
import { getLocalToken } from "./utils/auth"
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import '@/styles/progress.scss'
import { useUserStore } from "./stores/user";
import type { RouteRecordRaw } from "vue-router";
import { asyncRoutes } from "./router/asyncRoutes";
import {useMenuStore} from "@/stores/menu";

// 1. 定义白名单
const whiteList = ['/login', '/404']

/**
 * 获取一级权限点
 */
const getFirstRoutePerms = (perm: string[])=>{
    const newArr = perm.map((item: string)=>{
        return item.split(':')[0]
    })
    return [...new Set(newArr)]
}

/**
 * 获取二级权限点
 */
const getSecondRoutePerms = (perm: string[])=>{
    const newArr = perm.map((item: string)=>{
        const tempArr = item.split(':')
        return `${tempArr[0]}:${tempArr[1]}`
    })
    return [...new Set(newArr)]
}

/**
 * 根据权限点去筛选出路由
 */
const getRoutes = (
    firstRoutePerms: string[],
    secondRoutePerms: string[],
    asyncRoutes: RouteRecordRaw[]
) => {
    console.log(firstRoutePerms, secondRoutePerms, asyncRoutes, "-------");
    // 判断: 如果是管理员
    if(firstRoutePerms.includes('*')){
        return [...asyncRoutes]
    }
    const lastRoutes = asyncRoutes
        .filter((item: RouteRecordRaw) => {
            return firstRoutePerms.includes(item.meta!.permission!);
        })
        .map((item: RouteRecordRaw) => {
            return {
                ...item,
                children: item.children?.filter((r: RouteRecordRaw) =>
                    secondRoutePerms.includes(r.meta!.permission!)
                ),
            };
        });
    console.log(lastRoutes);
    return lastRoutes;
};

NProgress.configure({ showSpinner: false }); // 不显示旋转的进度条图标

// 2. 路由全局前置守卫
router.beforeEach(async (to, from, next)=>{
    // 2.0 开启进度条
    NProgress.start();
    // 2.1 获取token
    const token = getLocalToken()
    // 2.2 判断是否有token
    if(token){
        // 2.2.1 判断去的页面是否是登录页, 如果是则拦截到首页
        if(to.path === '/login'){
            next('/')
        } else {
            // 2.2.2 获取用户权限数据
            const store = useUserStore()
            if(!store.profile.id){
                const res = await store.getProfile();
                const menu = getFirstRoutePerms(res.permissions);
                const sMenu = getSecondRoutePerms(res.permissions);
                // 2.2.3 根据权限标识 过滤筛选 动态路由表 最终得到有资格显示到左侧的所有路由表
                const perRoutes = getRoutes(menu, sMenu, asyncRoutes);
                // 2.2.4 把动态路由表加入到路由系统中（当浏览器中访问路由的路径 显示渲染出来对应的组件）
                perRoutes.push({
                    path: "/:pathMatch(.*)*",
                    component: () => import("@/views/NotFound.vue"),
                    meta: { hidden: true },
                    children: []
                });
                perRoutes.forEach((route: any) => {
                    router.addRoute(route);
                });
                // 把动态路由数组给到仓库(考虑左侧菜单渲染)
                const menuStore = useMenuStore();
                menuStore.setMenuList(perRoutes as RouteRecordRaw[]);
                next({...to})
            }
            next()
        }
    }else{
        // 2.2.2 判断是否在白名单
        if(!whiteList.includes(to.path)){
            next('/login')
        }else{
            next()
        }
    }
})

// 3. 路由后置守卫
router.afterEach((to, from)=>{
    NProgress.done();
    document.title = to.meta.title || '黑马智数-three'
})